<template>
  <el-drawer :title="dialogTitle" v-model="dialogVisible" size="85%">
    <el-row :gutter="6" class="row">
      <el-col :md="24" :sm="24" :xs="24" :loading="loading">
        <el-card shadow="never" v-loading="loading">
          <template #header>
            <CardTitle title="发货/取件" />
          </template>
          <el-form
            ref="formRef"
            :model="formData"
            :rules="formRules"
            label-width="80px"
            v-loading="formLoading"
          >
            <el-row>
              <el-col :md="14" :sm="12" :xs="24" v-if="formData.collectType === '邮寄'">
                <el-form-item label="快递公司" prop="totalPrice">
                  <el-input v-model="formData.deliveryName" class="!w-300px" placeholder="请输入快递公司名称" />
                </el-form-item>
                <el-form-item label="快递单号" prop="totalPrice">
                  <el-input v-model="formData.deliveryNo" class="!w-300px" placeholder="请输入快递单号" />
                </el-form-item>

                <el-form-item>
                  <el-button @click="submitForm('pass')" type="primary" :disabled="formLoading">确认发货</el-button>
                </el-form-item>

              </el-col>
              <el-col :md="14" :sm="12" :xs="24" v-else>

                <el-form-item>
                  <el-button @click="submitForm('pass')" type="primary" :disabled="formLoading">通知取件</el-button>
                </el-form-item>

              </el-col>

            </el-row>

          </el-form>
        </el-card>

      </el-col>

    </el-row>

    <el-skeleton :loading="loading" animated>
      <MedicalCopyDetailForm :data="formData" />
    </el-skeleton>


    <template #footer>
      <el-button @click="dialogVisible = false" type="danger">关 闭</el-button>
    </template>
  </el-drawer>
</template>
<script setup lang="ts">
import { DICT_TYPE, getStrDictOptions, getDictOptions, getIntDictOptions } from '@/utils/dict'
import { MedicalCopyApi, MedicalCopyVO } from '@/api/hospital/medicalcopy'
import MedicalCopyDetailForm from './MedicalCopyDetailForm.vue'

/** 病案复印 表单 */
defineOptions({ name: 'MedicalCopyForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const loading = ref(true) // 加载中

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  orgId: undefined,
  orgName: undefined,
  orgCode: undefined,
  applyNo: undefined,
  homepageId: undefined,
  leaveHospitalDate: undefined,
  leaveHospitalDept: undefined,
  leaveHospitalCertificate: undefined,
  hospitalNo: undefined,
  medicalType: undefined,
  purpose: undefined,
  content: undefined,
  relation: undefined,
  patientId: undefined,
  patientType: undefined,
  patientName: undefined,
  patientCardNo: undefined,
  patientCardImgFront: undefined,
  patientCardImgReverse: undefined,
  applicantName: undefined,
  applicantCardNo: undefined,
  applicantCardImgFront: undefined,
  applicantCardImgReverse: undefined,
  otherFile: undefined,
  collectType: undefined,
  recipientName: undefined,
  recipientPhone: undefined,
  recipientAddress: undefined,
  deliveryId: undefined,
  deliveryName: undefined,
  deliveryNo: undefined,
  orderNumber: undefined,
  thirdOrderNo: undefined,
  totalPrice: 0,
  medicalPrice: 0,
  printPrice: 0,
  postagePrice: 0,
  servicePrice: 0,
  otherPrice: 0,
  payStatus: undefined,
  payTime: undefined,
  payType: undefined,
  refundNumber: undefined,
  refundPrice: undefined,
  refundTime: undefined,
  refundReason: undefined,
  examine: undefined,
  remark: undefined,
  status: undefined,
  patientCardImgHandheld: undefined,
  applicantCardImgHandheld: undefined
})
const formRules = reactive({
  totalPrice: [{ required: true, message: '总金额不能为空', trigger: 'blur' }],
  examine: [{ required: true, message: '审核意见不能为空', trigger: 'blur' }],
  applyNo: [{ required: true, message: '申请单号不能为空', trigger: 'blur' }],
  medicalType: [{ required: true, message: '病案类型不能为空', trigger: 'change' }],
  purpose: [{ required: true, message: '用途不能为空', trigger: 'blur' }],
  content: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
  relation: [{ required: true, message: '申请人与病人关系不能为空', trigger: 'blur' }],
  patientId: [{ required: true, message: '病人ID不能为空', trigger: 'blur' }],
  patientName: [{ required: true, message: '病人姓名不能为空', trigger: 'blur' }],
  patientCardNo: [{ required: true, message: '病人证件号不能为空', trigger: 'blur' }],
  collectType: [{ required: true, message: '收取方式不能为空', trigger: 'change' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = '病案复印审核'
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    loading.value = true
    try {
      formData.value = await MedicalCopyApi.getMedicalCopy(id)
    } finally {
      loading.value = false
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/**
 * 【ERP】格式化 Input 数字
 *
 * @param num 数量
 * @package digit 保留的小数位数
 * @return 格式化后的数量
 */
const handlePrice = (num: number | string | undefined, digit: number) => {
  if (num == null) {
    return ''
  }
  if (typeof num === 'string') {
    num = parseFloat(num)
  }
  // 如果非 number，则直接返回空串
  if (isNaN(num)) {
    return ''
  }
  return num.toFixed(digit)
}


/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async (type :String ) => {
  if (formData.value.collectType === '邮寄') {
    formData.value.status = 1;
    formData.value.examine = '审核通过';
    if(!formData.value.deliveryName){
      message.error('请输入快递公司名称')
      return
    }
    if(!formData.value.deliveryNo){
      message.error('请输入快递单号')
      return
    }
  }

  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as MedicalCopyVO
    const result = await MedicalCopyApi.sendMedicalCopy(data)
    message.success('操作成功')
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    orgId: undefined,
    orgName: undefined,
    orgCode: undefined,
    applyNo: undefined,
    homepageId: undefined,
    leaveHospitalDate: undefined,
    leaveHospitalDept: undefined,
    leaveHospitalCertificate: undefined,
    hospitalNo: undefined,
    medicalType: undefined,
    purpose: undefined,
    content: undefined,
    relation: undefined,
    patientId: undefined,
    patientType: undefined,
    patientName: undefined,
    patientCardNo: undefined,
    patientCardImgFront: undefined,
    patientCardImgReverse: undefined,
    applicantName: undefined,
    applicantCardNo: undefined,
    applicantCardImgFront: undefined,
    applicantCardImgReverse: undefined,
    otherFile: undefined,
    collectType: undefined,
    recipientName: undefined,
    recipientPhone: undefined,
    recipientAddress: undefined,
    deliveryId: undefined,
    deliveryName: undefined,
    deliveryNo: undefined,
    orderNumber: undefined,
    thirdOrderNo: undefined,
    totalPrice: undefined,
    medicalPrice: undefined,
    printPrice: undefined,
    postagePrice: undefined,
    servicePrice: undefined,
    otherPrice: undefined,
    payStatus: undefined,
    payTime: undefined,
    payType: undefined,
    refundNumber: undefined,
    refundPrice: undefined,
    refundTime: undefined,
    refundReason: undefined,
    examine: undefined,
    remark: undefined,
    status: undefined,
    patientCardImgHandheld: undefined,
    applicantCardImgHandheld: undefined
  }
  formRef.value?.resetFields()
}
</script>

<style scoped>
:deep(.el-input-group__append) {
  padding: 0 5px;
}

:deep(.el-text) {
  color: #000000;
}

.medical-record-table {
  border-collapse: collapse;
  width: 100%;
  border: 1px solid #f2f3f5;
  table-layout: fixed;
}
.medical-record-table th, td {
  border: 1px solid #f2f3f5;
  padding: 3px 5px;
  text-align: left;
  height: 20px;
  overflow: hidden;
  font-size: 14px;
  color: #000000;
}
.medical-record-fill-color{
  background-color: #f5f7fa;
  border: 1px solid #f2f3f5;
  font-weight: bolder;
  color: #606266;
}
.dawn-color-flag {
  color: #dc2e2e !important;
  font-weight: 700;
}
.img-box{
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.img-box-img{
  width: 80px;
  height: 50px;
}
.img-box-text{
  margin-top: 3px;
}
</style>
